#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
"""
@author:apple
@file:replace_file.py
@time:2021/06/29
"""
import os


def method01(file_path):
    """
    使用内存存放全部文件数据，处理之后再写回硬盘文件中
    """
    if not os.path.exists(file_path):
        print(f'{file_path} not exists')
        return
    tmp_context = []
    with open(file_path, mode='rt', encoding='utf-8') as f:
        ...
        for line in f:
            ...
            tmp_context.append(line.replace('a', 'A'))

    with open(file_path, mode='wt', encoding='utf-8') as f:
        for ctx in tmp_context:
            f.write(ctx)


def method02(file_path):
    """
    使用 临时文件存储处理过的字符，处理完成后删除原来的文件，并重命名临时文件为原来的文件名
    """
    if not os.path.exists(file_path):
        print('{} not exists'.format(file_path))
        return
    tmp_path = os.path.join(os.path.dirname(file_path), '.swap')

    with open(file_path, mode='rt', encoding='utf-8') as readFile, \
            open(tmp_path, mode='wt', encoding='utf-8') as writeFile:
        ...
        for read_context in readFile:
            writeFile.write(read_context.replace('A', 'a'))

    os.remove(file_path)
    os.rename(tmp_path, file_path)


if __name__ == '__main__':
    pass
    method02('./tail_f.txt')
